/*
 * Copyright (C) 2015-2019 Alibaba Group Holding Limited
 */

#include <stdio.h>
#include <stdlib.h>

#include "aos/kernel.h"
#include "aos/hal/adc.h"
#include "app_entry.h"

/********************************************************************************
type     -- the adc output convert(voltage/current/none), user do the calibration
n        -- test times
delay_ms -- delay time between tests  in ms
**********************************************************************************/
int test_adc(adc_data_type_e type, int n, int delay_ms)
{
    int ret;
    volatile int count = n;
    float voltage;
    float current;
    adc_dev_t adc;
    uint16_t value;

    printf("enter adc test\r\n");

    ret = hal_adc_init(&adc);
    if (ret != 0) {
        printf("hal_adc_init fail 0x%08x\r\n", ret);
        return -1;
    }

    while(1) {
        for (int j = 0; j < 8; j++) {
            adc.port = j;
            ret = hal_adc_value_get(&adc, &value, 0x1000);
            if (type == ADC_TYPE_VOLTAGE) {
                voltage = (float)value * 10/4096;
                printf("adc port %d : ret = %d, value = %d  voltage = %.3f V\r\n",  adc.port, ret, value, voltage);

            }
            else if (type == ADC_TYPE_CURRENT) {
                current = (float)value / 200;
                printf("adc port %d : ret = %d, value = %d  current = %.3f MA\r\n",  adc.port, ret, value, current);
            }

            else {
                printf("adc port %d : ret = %d, value = %d\r\n",  adc.port, ret, value);

            }
        }

        printf("\n\r");

        aos_msleep(delay_ms);
    }

    ret = hal_adc_finalize(&adc);
    if (ret != 0) {
        printf("hal_adc_init fail 0x%08x\r\n", ret);
        return -1;
    }

    return 0;
}


